import datetime

from django.conf import settings
from django.http import QueryDict
from django.template import Library
from django.urls import reverse
from django.utils.safestring import mark_safe

from web import models

register = Library()


def check_permission(request, name):
    role = request.mobiledj_user.role

    permission_dict = settings.MOBILEDJ_PERMISSION[role]

    if name in permission_dict:
        return True
    if name in settings.MOBILEDJ_PERMISSION_PUBLIC:
        return True


@register.simple_tag
def add_permission(request, name, *args, **kwargs):
    if not check_permission(request, name):
        return ""
    url = reverse(name, args=args, kwargs=kwargs)
    tpl = """
    <a class="btn btn-success" href="{}"><span class="glyphicon glyphicon-plus-sign"></span> 新建</a>
    """.format(url)
    return mark_safe(tpl)


@register.simple_tag
def edit_permission(request, name, *args, **kwargs):
    if not check_permission(request, name):
        return ""
    url = reverse(name, args=args, kwargs=kwargs)

    param = request.GET.urlencode()
    if param:
        new_query_dict = QueryDict(mutable=True)
        new_query_dict['_filter'] = param
        param_string = new_query_dict.urlencode()
        tpl = """
        <a class="btn btn-primary btn-xs" href="{}?{}">编辑</a>
        """.format(url, param_string)
        return mark_safe(tpl)
    tpl = """
         <a class="btn btn-primary btn-xs" href="{}">编辑</a>
         """.format(url)
    return mark_safe(tpl)


@register.simple_tag
def delete_permission(request, name, *args, **kwargs):
    if not check_permission(request, name):
        return ""
    pk = kwargs.get('pk')
    tpl = """
    <a cid="{}" class="btn btn-danger btn-xs btn-delete" href="#">删除</a>
    """.format(pk)
    return mark_safe(tpl)


@register.filter
def has_permission(request, others):
    name_list = others.split(',')
    for name in name_list:
        status = check_permission(request, name)
        if status:
            return True
    return False


@register.simple_tag
def blockip_permission(request, name, *args, **kwargs):
    if not check_permission(request, name):
        return ""
    now = datetime.datetime.now()
    current_time = now.time()
    specific_time = datetime.time(hour=15, minute=00, second=0, microsecond=0)

    specific_datetime = datetime.datetime(year=now.year,
                                          month=now.month,
                                          day=now.day,
                                          hour=0,
                                          minute=0,
                                          second=0,
                                          microsecond=0)

    name_list = name.split('_')
    if name_list[0] == 'botgate':
        botgate_obj = models.Botgate.objects.filter(id=kwargs.get('pk')).first()
        date_time = botgate_obj.create_datetime
    elif name_list[0] == 'sangfor':
        skyeye_obj = models.SangforFw.objects.filter(id=kwargs.get('pk')).first()
        date_time = skyeye_obj.create_datetime
    elif name_list[0] == 'skyeye':
        skyeye_obj = models.SkyEye.objects.filter(id=kwargs.get('pk')).first()
        date_time = skyeye_obj.create_datetime
    if date_time < specific_datetime:
        return ""

    # 解除封锁按钮显示
    src_ip = kwargs.get('src_ip')
    is_display = False
    if name == 'botgate_block_ip':
        # 如果是当天已经封禁的IP，封禁按钮不显示
        blockip_obj = models.BlockIp.objects.filter(create_datetime__year=date_time.year,
                                                    create_datetime__month=date_time.month,
                                                    create_datetime__day=date_time.day,
                                                    block_device='botgate',
                                                    src_ip=src_ip).first()
        # 没有解除封禁的IP，封禁按钮不显示
        blockip_obj1 = models.BlockIp.objects.filter(unblock_datetime__gt=now,
                                                     block_device='botgate',
                                                     src_ip=src_ip).first()
        if blockip_obj1 or blockip_obj:
            is_display = True
    else:
        blockip_obj = models.BlockIp.objects.filter(create_datetime__year=date_time.year,
                                                    create_datetime__month=date_time.month,
                                                    create_datetime__day=date_time.day,
                                                    block_device='sangfor_fw',
                                                    unblock_datetime__gt=now,
                                                    src_ip=src_ip).first()
        blockip_obj1 = models.BlockIp.objects.filter(unblock_datetime__gt=now,
                                                     block_device='sangfor_fw',
                                                     src_ip=src_ip).first()

        if blockip_obj or blockip_obj1:
            is_display = True

    if is_display:
        return ""

    url = reverse(name, args=args, kwargs=kwargs)

    param = request.GET.urlencode()
    if param:
        new_query_dict = QueryDict(mutable=True)
        new_query_dict['_filter'] = param
        param_string = new_query_dict.urlencode()
        tpl = """
        <a class="btn btn-primary btn-sm" href="{}?{}">封禁IP</a>
        """.format(url, param_string)
        return mark_safe(tpl)

    tpl = """
         <a class="btn btn-primary btn-sm" href="{}">封禁IP</a>
         """.format(url)
    return mark_safe(tpl)


@register.simple_tag
def unblockip_permission(request, name, *args, **kwargs):
    if not check_permission(request, name):
        return ""

    current_time = datetime.datetime.now()
    pk = kwargs.get('pk')
    obj = models.BlockIp.objects.filter(id=pk, unblock_datetime__lt=current_time).first()
    if obj:
        return ""

    url = reverse(name, args=args, kwargs=kwargs)
    param = request.GET.urlencode()
    if param:
        new_query_dict = QueryDict(mutable=True)
        new_query_dict['_filter'] = param
        param_string = new_query_dict.urlencode()
        tpl = """
        <a class="btn btn-primary btn-sm" href="{}?{}">解封IP</a>
        """.format(url, param_string)
        return mark_safe(tpl)
    tpl = """
         <a class="btn btn-primary btn-sm" href="{}">解封IP</a>
         """.format(url)
    return mark_safe(tpl)
